<template>
  <el-card class="good-container">
    <template #header>
      <div class="header">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">新增用户</el-button>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="getGoodList">刷新数据</el-button>
      </div>
    </template>
    <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="adminUserId"
          label="编号"
      >
      </el-table-column>
      <el-table-column
          prop="loginUserName"
          label="账户"
      >
      </el-table-column>
      <el-table-column
          prop="nickName"
          label="昵称"
      >
      </el-table-column>
      <el-table-column
          label="状态"
      >
        <template #default="scope">
          <span style="color: green;" v-if="scope.row.lock == 0">未锁定</span>
          <span style="color: red;" v-else>已锁定</span>
        </template>
      </el-table-column>

      <el-table-column
          label="操作"
          width="100"
      >
        <template #default="scope">
          <a style="cursor: pointer; margin-right: 10px" @click="handleEdit(scope.row.goodsId)">修改</a>
        </template>
      </el-table-column>
    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="changePage"
    />
    <el-dialog v-model="open" :close-on-click-modal="false" title="新增用户">
      <div class="add">
        <el-card class="add-container">
          <el-form :model="form" :rules="rules" ref="goodRef" label-width="100px" class="form">
            <el-form-item label="账户" prop="loginUserName">
              <el-input style="width: 300px" v-model="form.loginUserName" placeholder="请输入账户"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="loginPassword">
              <el-input style="width: 300px" v-model="form.loginPassword" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="originalPrice">
              <el-input style="width: 300px" v-model="form.nickName" placeholder="请输入昵称"></el-input>
            </el-form-item>
            <el-form-item label="锁定状态" prop="goodsSellStatus">
              <el-radio-group v-model="form.lock">
                <el-radio :label="0">未锁定</el-radio>
                <el-radio :label="1">已锁定</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitAdd">{{ form.id ? '立即修改' : '立即创建' }}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {onMounted, reactive, ref, toRefs} from 'vue'
import axios from '@/utils/axios'
import {ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'
import md5 from 'js-md5'
import {encryptRSA} from '@/utils/jsencrypt'
import {encryptByAES, createAesKey, decryptByAES} from '@/utils/cryptoutils'
import {toBase64, decode} from 'js-base64'

export default {
  name: 'User',
  setup() {
    const goodRef = ref(null)
    const multipleTable = ref(null)
    const router = useRouter()
    const state = reactive({
      loading: false,
      tableData: [], // 数据列表
      multipleSelection: [], // 选中项
      total: 0, // 总条数
      currentPage: 1, // 当前页
      pageSize: 10, // 分页大小
      open: false,
      form: {
        nickName: null,
        loginUserName: null,
        loginPassword: null,
        lock: 0
      },
      rules: {
        nickName: [
          {required: 'true', message: '昵称必填', trigger: ['change']}
        ],
        loginUserName: [
          {required: 'true', message: '账户必填', trigger: ['change']}
        ],
        loginPassword: [
          {required: 'true', message: '密码必填', trigger: ['change']}
        ],
      }
    })
    onMounted(() => {
      getGoodList()
      testData()
    })
    // 获取轮播图列表
    const getGoodList = () => {
      state.loading = true
      axios.get('/adminUser/list', {
        params: {
          pageNum: state.currentPage,
          pageSize: state.pageSize
        }
      }).then(res => {
        if (md5(res.timestamp + res.securityKey + res.secretData) !== res.signature) {
          return ElMessage.warning({
            message: '数据已被篡改'
          })
        }
        let result = decryptByAES(res.secretData, res.securityKey, res.securityKey)
        result = JSON.parse(result)
        state.tableData = result.data.records
        state.total = result.data.total
        state.currentPage = result.data.current
      }).catch(e => {
        console.log('e = ', e)
      }).finally(() => {
        state.loading = false
      })
    }
    const handleAdd = () => {
      // router.push({ path: '/add' })
      state.open = true
      state.form = {
        nickName: null,
        loginUserName: null,
        loginPassword: null,
        lock: 0
      }
    }
    const handleEdit = (id) => {
      // router.push({ path: '/add', query: { id } })
    }
    // 选择项
    const handleSelectionChange = (val) => {
      state.multipleSelection = val
    }
    const changePage = (val) => {
      state.currentPage = val
      getGoodList()
    }
    const handleStatus = (id, status) => {
      axios.put(`/adminUser/lock`, {
        adminUserId: id,
        lock: status
      }).then(() => {
        ElMessage.success('修改成功')
        getGoodList()
      })
    }
    const submitAdd = () => {
      goodRef.value.validate((vaild) => {
        if (vaild) {
          let data = {
            timestamp: Math.ceil(Date.now() / 1000),
            signature: null,
            securityKey: null,
            secretData: null
          }
          state.form.loginPassword = md5(state.form.loginPassword)
          let key = createAesKey()
          data.securityKey = encryptRSA(key)
          let base64Key = toBase64(key)
          data.secretData = encryptByAES(JSON.stringify(state.form), base64Key, base64Key)
          data.signature = md5(data.timestamp + data.securityKey + data.secretData)
          axios.post('/adminUser/add', data).then(() => {
            ElMessage.success(state.form.id ? '修改成功' : '添加成功')
            state.open = false
            getGoodList()
          })
        }
      })
    }
    const testData = () => {

    }
    return {
      ...toRefs(state),
      multipleTable,
      handleSelectionChange,
      handleAdd,
      handleEdit,
      getGoodList,
      changePage,
      handleStatus,
      submitAdd,
      goodRef
    }
  }
}
</script>

<style scoped>
.good-container {
  min-height: 100%;
}

.el-card.is-always-shadow {
  min-height: 100% !important;
}
</style>
